//
//  DGSessionManager.m
//  DGCarDriver
//
//  Created by 位立志 on 2018/4/2.
//  Copyright © 2018年 Bwton. All rights reserved.
//

#import "SJZAFNSessionManager.h"
#import "AFNetworking.h"
#import "SJZNetWorkTools.h"

#ifdef DEBUG
#define PPLog(...) printf("[%s] %s [第%d行]: %s\n", __TIME__ ,__PRETTY_FUNCTION__ ,__LINE__, [[NSString stringWithFormat:__VA_ARGS__] UTF8String])
#else
#define PPLog(...)
#endif
@interface SJZAFNSessionManager ()
@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;

@end

@implementation SJZAFNSessionManager

singleton_m(SJZAFNSessionManager);

#define kRequestTime @"RequestTime"
#define kRequestType @"RequestType"
#define kParameters  @"parameters"
#define kResponse    @"response"
#define kError       @"error"

static AFHTTPSessionManager *_sessionManager;

- (void)setValue:(NSString *)value forHttpField:(NSString *)field {
    [self.sessionManager.requestSerializer setValue:value forHTTPHeaderField:field];
}

-(AFHTTPSessionManager *)sessionManager {
    if (!_sessionManager) {
        _sessionManager = [[AFHTTPSessionManager alloc] init];
        _sessionManager.requestSerializer.timeoutInterval = 10.f;
        _sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
        _sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
        _sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/json", @"text/plain", @"text/javascript", @"text/xml", @"image/*",@"text/encode", nil];

    }
    return _sessionManager;
}



- (NSURLSessionTask *)GET:(NSString *)URL
               parameters:(id)parameters
                  success:(void(^)(id SuccessResponse))success
                  failure:(void(^)(NSError *error))failure {

    NSAssert([URL length], @"url不能为空");
    // 处理请求头
//    [self handleHttpHeader];
    
    NSURLSessionTask *sessionTask = [_sessionManager GET:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
        success ? success(responseObject) : nil;
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure ? failure(error) : nil;
        
    }];
    
    return sessionTask;
}


- (NSURLSessionTask *)POST:(NSString *)URL
               parameters:(id)parameters
                  success:(void(^)(id SuccessResponse))success
                  failure:(void(^)(NSError *error))failure {
    
    // 处理请求头。 加签
//    [self handleHttpHeaderWithParams:parameters];
    NSLog(@"请求url = %@",URL);
    NSLog(@"请求参数 = %@",parameters);
    NSURLSessionTask *sessionTask = [_sessionManager POST:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        
//        NSLog(@"%@",task.response);
//        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
//        NSDictionary *allHeaders = response.allHeaderFields;
        
//        NSString *jsonStr = [self dictionaryToJson:responseObject];
//        NSString *jsonStr = [self handleDict:responseObject Encoded:NO];
//        NSLog(@"%@",jsonStr);
        
        
//        NSString *sha256Str = [jsonStr md5String];
//        NSString *sha256Str2 = [sha256Str hmac:sha256Str withKey:HMAC256Key];
//        NSString *sha256Str3 = [sha256Str2 base64Encoding];
//
//
//        if ([sha256Str3 isEqualToString:allHeaders[@"Signature"]]) {
//            NSLog(@"验证通过");
//        }else
//        {
//            NSLog(@"验证失败");
//        }
        
        success ? success(responseObject) : nil;
        NSLog(@"请求成功%@",responseObject);

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        failure ? failure(error) : nil;
        NSLog(@"请求失败%@",error);
        
    }];
    
    return sessionTask;
}

- (void)handleHttpHeaderWithParams:(id)parameters{
    
    NSString *random = [SJZNetWorkTools random:6];
    NSString *timeStamp = [SJZNetWorkTools timeStamp];
    
    [self setValue:KAPPID forHttpField:@"AppId"];
    [self setValue:timeStamp forHttpField:@"Timestamp"];
    [self setValue:random forHttpField:@"Nonce"];
    
//    NSDictionary *dict = @{@"bbb":@"你好",@"aaa":@"哈哈",};
    
    NSString *str = [self dictionaryToJson:parameters];
//    NSString *str = [self handleDict:parameters Encoded:NO];

    NSLog(@"%@",str);
    NSString *str2 = [str SHA256];
    NSLog(@"%@",str2);
    
    NSString *str3 = [NSString stringWithFormat:@"%@%@%@%@",KAPPID,timeStamp,random,str2];
    NSLog(@"%@",str3);
    
    NSString *encoprt = [SJZNetWorkTools requestSign:str3];
    NSLog(@"%@",encoprt);
    
    NSString *encoprt2 = [encoprt base64Encoding];
    [self setValue:encoprt2 forHttpField:@"Signature"];
}

// 字典转json， 并去掉空格 换行。
- (NSString *)dictionaryToJson:(id)object
{
    
    NSString *jsonString = [[NSString alloc]init];
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
                        
                                                       options:NSJSONWritingPrettyPrinted
                        
                                                         error:&error];
    
    if (! jsonData) {
        
        NSLog(@"error: %@", error);
        
    } else {
        
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    [mutStr replaceOccurrencesOfString:@" "withString:@""options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    [mutStr replaceOccurrencesOfString:@"\n"withString:@""options:NSLiteralSearch range:range2];
    
    return mutStr;
    
}

- (NSString *)handleDict:(NSMutableDictionary *)tmpDict Encoded:(BOOL)bEncoded{
    
    // NOTE: 排序，得出最终请求字串
    NSArray* sortedKeyArray = [[tmpDict allKeys] sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return [obj1 compare:obj2];
    }];
    
    NSMutableArray *tmpArray = [NSMutableArray new];
    for (NSString* key in sortedKeyArray) {
        NSString* orderItem = [self orderItemWithKey:key andValue:[tmpDict objectForKey:key] encoded:bEncoded];
        if (orderItem.length > 0) {
            [tmpArray addObject:orderItem];
        }
    }
    
    return [tmpArray componentsJoinedByString:@"&"];
}

- (NSString*)orderItemWithKey:(NSString*)key andValue:(NSString*)value encoded:(BOOL)bEncoded
{
    if (key.length > 0 && value.length > 0) {
        if (bEncoded) {
            value = [self encodeValue:value];
        }
        return [NSString stringWithFormat:@"%@=%@", key, value];
    }
    return nil;
}

- (NSString*)encodeValue:(NSString*)value
{
    NSString* encodedValue = value;
    if (value.length > 0) {
        NSCharacterSet *charset = [[NSCharacterSet characterSetWithCharactersInString:@"!*'();:@&=+$,/?%#[]"]invertedSet];
        encodedValue = [value stringByAddingPercentEncodingWithAllowedCharacters:charset];
    }
    return encodedValue;
}


/**
 *  json转字符串
 */
- (NSString *)jsonToString:(id)data {
    // 有时出现报错。
//    if(data == nil) { return nil; }
//    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
//    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    return nil;
}


#pragma mark - 初始化AFHTTPSessionManager相关属性

@end
